package me.duzhi.ilog.cms.function;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import io.jpress.model.Content;
import io.jpress.model.Metadata;
import io.jpress.model.User;
import io.jpress.model.query.MetaDataQuery;
import io.jpress.utils.HttpUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.math.BigInteger;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class Functions
{
    public static Log log = Log.getLog(Functions.class);


    public  static class Kit{
        private static final Prop prop = PropKit.use("other.properties");

        public static String get(String key) {
            return prop.get(key);
        }

        public static String get(String key, String defaultValue) {
            return prop.get(key, defaultValue);
        }

        public static Integer getInt(String key) {
            return prop.getInt(key);
        }

        public static Integer getInt(String key, Integer defaultValue) {
            return prop.getInt(key, defaultValue);
        }

        public static Long getLong(String key) {
            return prop.getLong(key);
        }

        public static Long getLong(String key, Long defaultValue) {
            return prop.getLong(key, defaultValue);
        }

        public static Boolean getBoolean(String key) {
            return prop.getBoolean(key);
        }

        public static Boolean getBoolean(String key, Boolean defaultValue) {
            return prop.getBoolean(key, defaultValue);
        }

        public static boolean containsKey(String key) {
            return prop.containsKey(key);
        }

        public static Properties getProperties() {
            return prop.getProperties();
        }
    }


    public static final Map<String, Integer> finalStar = new HashMap();
    public static final String attr_ratesdes = "_duzhi_ratesdes";
    public static final String attr_ratingCount = "_duzhi_ratingCount";
    public static final String attr_ratingValue = "_duzhi_ratingValue";

    public static void setMetaData(BigInteger id, String sid)
    {
        Metadata _ratingValue = MetaDataQuery.me().findByTypeAndIdAndKey("content", id, "_duzhi_ratingValue");
        Metadata _ratingCount = MetaDataQuery.me().findByTypeAndIdAndKey("content", id, "_duzhi_ratingCount");
        Metadata _ratesdes = MetaDataQuery.me().findByTypeAndIdAndKey("content", id, "_duzhi_ratesdes");
        if (_ratingValue == null) {
            _ratingValue = newMetaData(id, "_duzhi_ratingValue");
            _ratingCount = newMetaData(id, "_duzhi_ratingCount");
            _ratesdes = newMetaData(id, "_duzhi_ratesdes");
        }
        if (Integer.valueOf(_ratingCount.getMetaValue() == null ? "0" : _ratingCount.getMetaValue()).intValue() == 0) {
            _ratingValue.setMetaValue(String.valueOf(finalStar.get(sid)));
            _ratingCount.setMetaValue("1");
            _ratesdes.setMetaValue(sid);
            _ratingValue.save();
            _ratingCount.save();
            _ratesdes.save();
        } else {
            _ratingCount.setMetaValue(String.valueOf(Integer.valueOf(_ratingCount.getMetaValue()).intValue() + 1));
            float __ratingValue = new Float(_ratingValue.getMetaValue()).floatValue();
            __ratingValue = (__ratingValue * Integer.valueOf(_ratingCount.getMetaValue()).intValue() + ((Integer)finalStar.get(sid)).intValue()) / (Integer.valueOf(_ratingCount.getMetaValue()).intValue() + 1);
            DecimalFormat fnum = new DecimalFormat("##0");
            _ratingValue.setMetaValue(String.valueOf(__ratingValue));
            String ___ratingValue = fnum.format(__ratingValue);
            _ratesdes.setMetaValue("star" + ___ratingValue);
            _ratingValue.update();
            _ratingCount.update();
            _ratesdes.update();
        }
    }

    private static Metadata newMetaData(BigInteger id, String attr_ratingValue)
    {
        Metadata metadata = new Metadata();
        metadata.setObjectType("content");
        metadata.setObjectId(id);
        metadata.setMetaKey(attr_ratingValue);
        return metadata;
    }

    private static void setMetaData(BigInteger id, String sid, String attr_ratesdes)
    {
    }

    static
    {
        finalStar.put("star3", Integer.valueOf(3));
        finalStar.put("star2", Integer.valueOf(2));
        finalStar.put("star1", Integer.valueOf(1));
        finalStar.put("star5", Integer.valueOf(5));
        finalStar.put("star4", Integer.valueOf(4));
    }

    public static final String OBJECT_TYPE_CONTENT = "content";
    public static final String META_KEY_ = "like";
    public static final String OBJECT_TYPE_USER = "user";

    public static void like(BigInteger pid, User user) {
        Metadata metadata = getMetadata(OBJECT_TYPE_CONTENT, META_KEY_, pid);
        if (metadata.getMetaValue() == null) {
            metadata.setMetaValue("1");
        } else {
            Integer likes = Integer.valueOf(metadata.getMetaValue()) + 1;
            metadata.setMetaValue(String.valueOf(likes));
        }
        metadata.saveOrUpdate();
        //保存用户喜好
        if (user != null) {
            Metadata userMeta = user.createMetadata(META_KEY_, String.valueOf(pid));
            userMeta.saveOrUpdate();
        }
    }

    private static Metadata getMetadata(String objectType, String metaKey, BigInteger pid) {
        Metadata metadata = MetaDataQuery.me().findByTypeAndIdAndKey(objectType, pid, metaKey);
        if (metadata == null) {
            metadata = new Metadata();
            metadata.setObjectType(objectType);
            metadata.setMetaKey(metaKey);
            metadata.setObjectId(pid);
        }
        return metadata;
    }

    public static String WechatGet(String message) throws Exception {
        Map param = new HashMap();
        param.put("question", message);
        Map header = new HashMap();
        header.put("Authorization", "APPCODE cc3b0903bc714e3ab5ce09ab573a5dbd");
        String result = HttpUtils.get("http://jisuznwd.market.alicloudapi.com/iqa/query", param, header);
        JSONObject jsonObject = JSON.parseObject(result);
        if ("0".equals(jsonObject.getString("status"))) {
            JSONObject __result = jsonObject.getJSONObject("result");
            return __result.getString("content");
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
        watchtt_io();
    }

    public static void watchtt_io() {
        //  System.out.println(HttpUtils.get("https://toutiao.io/k/xjxbq3"));
        String html = null;
        try {
            html = HttpUtils.get("https://toutiao.io/latest");
            Document doc = Jsoup.parse(html, String.valueOf(30));
            Elements elements = doc.getElementsByClass("post");
            for (int i = 0; i < elements.size(); i++) {
                Element element = elements.get(i);
                Element titleEl = element.select("h3.title a").first();
                String title = titleEl.text();
                String href = titleEl.attr("href");
                String _href = getRidictHref(getRidictHref(href));
                _href = _href.replaceAll("toutiao.io", "www.duzhi.me");
                Content content = new Content();
                content.setModule("tt");
                content.setTitle(title);
                content.setText(title);
                content.setText(title);
                content.setStatus(Content.STATUS_NORMAL);
                content.setCreated(new Date());
                content.setSlug(title);
                content.setSlug(title);
                Db.tx(new IAtom() {
                    @Override
                    public boolean run() throws SQLException {
                        return false;
                    }
                });
                Thread.sleep(5000);
            }
        } catch (Exception e) {
            log.error("load error",e);
        }
    }

    private static String getRidictHref(String href) throws Exception {
        Document _doc = Jsoup.parse(HttpUtils.get(href));
        return _doc.select("a").first().attr("href");
    }
}